"""
Session管理器
"""

from datetime import datetime, timedelta
from itertools import count
from typing import Dict, List, Optional

from crawlee.sessions import Session
from models.api_models import SessionInfo


class SessionManager:
    """Session管理器"""
    
    def __init__(self):
        self.sessions: Dict[str, Session] = {}
        self.session_counter = count()
    
    def create_session(self, max_usage_count: int = 50, max_age_hours: int = 2) -> Session:
        """创建新的Session"""
        session = Session(
            id=f"session_{next(self.session_counter)}",
            max_usage_count=max_usage_count,
            max_age=timedelta(hours=max_age_hours),
            max_error_score=20,
            blocked_status_codes=[403, 429, 503],
            user_data={
                'custom_cookies': {},
                'cookie_history': [],
                'created_by': 'api',
                'last_activity': datetime.now()
            }
        )
        self.sessions[session.id] = session
        return session
    
    def get_session(self, session_id: str) -> Optional[Session]:
        """获取指定Session"""
        return self.sessions.get(session_id)
    
    def get_all_sessions(self) -> List[SessionInfo]:
        """获取所有Session信息"""
        return [self._session_to_info(session) for session in self.sessions.values()]
    
    def get_usable_sessions(self) -> List[SessionInfo]:
        """获取可用的Session"""
        return [
            self._session_to_info(session) 
            for session in self.sessions.values() 
            if session.is_usable
        ]
    
    def delete_session(self, session_id: str) -> bool:
        """删除Session"""
        if session_id in self.sessions:
            del self.sessions[session_id]
            return True
        return False
    
    def cleanup_expired_sessions(self):
        """清理过期Session"""
        expired_ids = [
            sid for sid, session in self.sessions.items() 
            if not session.is_usable
        ]
        for sid in expired_ids:
            del self.sessions[sid]
        return len(expired_ids)
    
    def _session_to_info(self, session: Session) -> SessionInfo:
        """将Session转换为SessionInfo"""
        return SessionInfo(
            id=session.id,
            created_at=session._created_at,
            usage_count=session.usage_count,
            max_usage_count=session._max_usage_count,
            error_score=session.error_score,
            max_error_score=session._max_error_score,
            is_usable=session.is_usable,
            is_blocked=session.is_blocked,
            is_expired=session.is_expired,
            expires_at=session.expires_at,
            user_data=session.user_data
        ) 